/**
 * 
 */
package lt.vin.exaatto.client.ui;

import lt.vin.exaatto.client.events.ChatRemovedEvent;
import lt.vin.exaatto.client.events.ChatSelectedEvent;
import lt.vin.exaatto.client.events.NewChatEvent;
import lt.vin.exaatto.client.events.NewChatHandler;
import lt.vin.exaatto.shared.Chat;

import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;

/**
 * @author Vincentas
 *
 */
public class ChatPanel extends BaseContainerWidget<Chat> implements NewChatHandler {

	public ChatPanel() {
		super("Chats");
		
		textBox.setPlaceholder("Name for new chat...");
		
		Stat.getHandlerManager().addHandler(NewChatHandler.type, this);
	}

	@Override
	public void newChat(Chat chat) {
		addElement(chat);
		selectedElement(chat);
	}

	/* (non-Javadoc)
	 * @see lt.vin.exaatto.client.ui.BaseContainerWidget#markSelectedElement(java.lang.Object)
	 */
	@Override
	public void markSelectedElement(Chat element) {
		super.markSelectedElement(element);

		Stat.getHandlerManager().fireEvent(new ChatSelectedEvent(element));
	}

	/* (non-Javadoc)
	 * @see lt.vin.exaatto.client.ui.BaseContainerWidget#onRemoveElement(java.lang.Object)
	 */
	@Override
	public void onRemoveElement(final Chat chat) {
		Stat.getRpcService().deleteChat(chat.getId(), new AsyncCallback<Void>() {
			
			@Override
			public void onSuccess(Void result) {
				Stat.getHandlerManager().fireEvent(new ChatRemovedEvent(chat));
				removeElement(chat);				
			}
			
			@Override
			public void onFailure(Throwable caught) {
				Window.alert(caught.toString());				
			}
		});
	}

	@Override
	protected void newTextEntered(String text) {
		Stat.getRpcService().createNewChat(text, new AsyncCallback<Chat>() {
			
			@Override
			public void onSuccess(Chat result) {
				Stat.getHandlerManager().fireEvent(new NewChatEvent(result));		
			}
			
			@Override
			public void onFailure(Throwable caught) {
				Window.alert(caught.toString());
			}
		});		
	}
	
	
	
	
	
	

}
